
// my-app/src/util/actions/userAction.js
"use server";
import axios from 'axios';
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { cookies } from 'next/headers';

const baseUrl = "http://127.0.0.1:8000/api/usersss/";

export const fetchUserById = async (token) => {
  try {
    const response = await axios.get(`${baseUrl}profile`, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      },
    });
    const data = response.data;
    console.log("userAction:", data); // 添加这行代码查看返回的数据

    // 确保 data 是一个数组
    // if (!Array.isArray(data)) {
    //   throw new Error("Fetched user data is not an array");
    // }
    
    return response.data;
  } catch (error) {
    console.error("获取用户数据时出错:", error);
    throw new Error(error.response?.data?.message || "请你先登入");
  }
};

// 删除用户
export const deleteUser = async (token) => {
  try {
    const response = await axios.delete(`${baseUrl}profile`, {
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`,
      },
    });
    if (response.status === 200) {
      console.log("删除成功");
      revalidatePath("/usermanage");
      redirect("/usermanage");
    }
  } catch (error) {
    console.error("删除用户时出错:", error);
    throw new Error(error.response?.data?.message || "删除用户失败");
  }
};

// 更新用户信息
// export const updateUser = async (formData, token) => {
//   const { username, email, password } = formData;
//   try {
//     const response = await axios.put(`${baseUrl}profile`, {
//       username,
//       email,
//       password
//     }, {
//       headers: {
//         "Content-Type": "application/json",
//         "Authorization": `Bearer ${token}`,
//       },
//     });
//     if (response.status === 200) {
//       console.log("更新成功");
//       revalidatePath("/usermanage");
//       redirect("/usermanage");
//     }
//   } catch (error) {
//     console.error("更新用户数据时出错:", error);
//     throw new Error(error.response?.data?.message || "更新用户数据失败");
//   }
// };
export const updateUser = async (formData, token) => {
    const { username, email, password } = formData;
    try {
      const response = await axios.put(`${baseUrl}profile`, {
        username,
        email,
        password
      }, {
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${token}`,
        },
      });
      if (response.status === 200) {
        console.log("更新成功");
        return response.data;  // Ensure the success response is returned
      } else {
        throw new Error(response.data.message || "更新用户数据失败");
      }
    } catch (error) {
      console.error("更新用户数据时出错:", error);
      throw new Error(error.response?.data?.message || "更新用户数据失败");
    }
  };


